<?php
require_once(dirname(dirname(__FILE__)).'/init.php');
require_once(ROOT_PATH.'service/WxpayAPI/lib/WxPay.Api.php');
require_once(ROOT_PATH.'service/WxpayAPI/lib/WxPay.Notify.php');


class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);

		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}

	
	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{

		logs("Notify call back :".json_encode($data));
		$notfiyOutput = array();
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}

		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}

		//返回支付成功 --- 同步服务器
		$url  		=  HOST_URL.'/mobile/api/v1/wxPay.php';
		$timestamp 	=  time().mt_rand(1000,9999);

		$data['mode']		= 'order_success';
		$data['timestamp']	= $timestamp;
		$data['sign_code']	= serve_sign($timestamp);

		$result = $this -> httpApi($url,$data);
		if($result['code'] != 200 ){
			logs('获取订单异常:'.json_encode($result));
			return false;
		}

		return true;
	}



	/**
	 * [httpApi ]
	 * @Author   shouxue
	 * @DateTime 2017-11-01
	 * @version  v1.0
	 * @return   bool|mixed
	 */
	public function httpApi($url,$data){
		
		$result  = curlPost($url,$data);
		if(!$result){
			logs('call back: curl error');
			return false; 
		}

		if( preg_match('/^\xEF\xBB\xBF/', $result) ) {
	        $result = substr($result,3);
	    }

		$temp  = json_decode(trim($result, 3),true); 
		if(!$temp){
			logs('call back:'.json_encode($data).json_encode($result));
			return false; 
		}
		
		return $temp; 
	}	

}

logs("begin notify -----------");
$notify = new PayNotifyCallBack();
$notify->Handle(false);
logs("end notify -----------");


